import React, { useEffect, useRef, useState, useMemo } from 'react';
import { SchemaManage } from '@/components/SchemaComponent';
import { connect } from 'umi';
import { AssetacquisitionManageAPI } from '../common/type';
import { getTableColumns } from '../mconfig';
import { PlusOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { fieldFlowExport, getKeyRouter, getTenantID } from '@/utils';
import { CancelModal } from '@/components/CancelModal';
import { ILoadMapTypeAll } from '@/common';
import { message } from 'antd';
import { RevokeModal } from '@/pages/AssetManage/Acomponents/RevokeModal';
import { ExportServices, InventorySummaryManageServices, completeServices } from '../services/ManageServices';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { deleteApplyManageService } from '../services/UpdataService';

const AssetAcquisitionManageView: React.FC<AssetacquisitionManageAPI.IMaterialManageView> = ({ curRes }) => {
  /**管理页services*/
  const { data, loading, searchList, pagination, reloadRequest, manageTableParams } = InventorySummaryManageServices(curRes);

  /**是否显示作废弹窗*/
  const [isShowCancelModal, setIsShowCancelModal] = useState<Record<string, any>>({
    isShow: false,
    recordObj: {},
  });

  /**是否显示撤销弹窗*/
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/

  /** 删除提示框 */
  const [openTipInfoModal, setOpenTipInfoModal] = useState<Record<string, any>>({
    checkRowObj: {},
    showModal: false,
  });

  /** 删除弹框关闭 */
  const tipOnClose = () => {
    setOpenTipInfoModal({
      checkRowObj: {},
      showModal: false,
    });
  };

  /** 删除申请回调 */
  const deleteApplyManageCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };

  /** 删除申请 */
  const { deleteApplyManageRun, deleteApplyManageLoading } = deleteApplyManageService(deleteApplyManageCallback);

  useEffect(() => {
    if (history.location.pathname == '/inventorySummaryController/manage') {
      reloadRequest({});
    }
  }, [history.location.pathname]);

  const completeCallback = (res: any) => {
    if (res.msgFlag == true) {
      message.success(res.msg);
      reloadRequest({});
    } else {
      message.error(res.msg);
    }
  };

  const { completeRun } = completeServices(curRes, completeCallback);

  const [titleValue, setTitleValue] = useState(null);

  /** 导出回调 */
  const exportCallback = (res: any) => {
    fieldFlowExport(res, `${titleValue}.db`);
  };

  // 导出接口
  const { ExportRun } = ExportServices(exportCallback, curRes);
  /**管理页的ref*/
  const MaterialManageViewRef: any = useRef();

  /**  是否展开当前流程节点弹框 */
  const [openOtherFuncModal, setOpenOtherFuncModal] = useState<Record<string, any>>({
    openNodeImage: false,
    selectRows: {},
    openAddSignModal: false,
  });

  /**切换头部方法*/
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    reloadRequest({ ...params, ...searchValues });
  };

  /**重置方法*/
  const onReset = (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
    reloadRequest({ ...reqParams });
  };

  /**搜索方法*/
  const onSearch: any = (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
    reloadRequest({ ...reqParams });
  };

  /**分页方法*/
  const onPageChange = (current: any, pageSize: any, params: any) => {
    reloadRequest({ pageSize, current, ...params });
  };

  /**刷新管理页面的办法*/
  const reloadManage = () => {
    reloadRequest({ ...manageTableParams });
  };

  /**Table操作列的事件池*/
  const getTableOperateFuncs: any = {
    /**编辑按钮*/
    onEdit(record: any) {
      history.push({
        pathname: `/assetInventoryDifference/edit/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'edit',
          record: record,
          returnPathName: history.location.pathname,
        },
      });
    },
    /**详情按钮*/
    onView(record: any) {
      history.push({
        pathname: `/assetInventoryDifference/details/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          record: record,
          returnPathName: history.location.pathname,
        },
      });
    },
    /**作废按钮*/
    // onCancel(record: any) {
    //   setIsShowCancelModal({
    //     isShow: true,
    //     recordObj: record,
    //   });
    // },
    /** 删除按钮 */
    onCancel: (record: Record<string, any>) => {
      setOpenTipInfoModal({
        checkRowObj: record,
        showModal: true,
      });
    },

    /**撤销按钮*/
    onRevoke(record: any) {
      setInvalidState({ isShow: true, resObj: record });
    },
    onOAdetail(record: any) {
      history.push({
        pathname: `/assetInventoryDifference/dealHomePage/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          record: record,
          returnPathName: history.location.pathname,
        },
      });
    },
    onComplete(record: any) {
      completeRun(record);
    },
    onChangeOver(record: any) {
      console.log(record, 'record');
    },
  };

  /**Table的columns集合*/
  const getTableColumn: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, getTableOperateFuncs);
  }, [curRes]);

  /**新增操作按钮*/
  const actionList: AssetacquisitionManageAPI.IActionList = useMemo(() => {
    return [
      {
        title: '添加',
        // visible: curRes?.['/assetInventory/add'] || false,
        visible: true,
        type: 'primary',
        icon: <PlusOutlined />,
        onClick: () => {
          history.push({
            pathname: `/assetInventoryDifference/add/:${getKeyRouter()}${getKeyRouter()}`,
            state: {
              pageType: 'add',
              returnPathName: history.location.pathname,
            },
          });
        },
      },
    ];
  }, [curRes]);

  return (
    <>
      <div
        id={'custom-preview-container'}
        style={{
          position: 'relative',
          overflow: 'hidden',
          height: '100%',
          width: '100%',
        }}
      >
        <SchemaManage
          ref={MaterialManageViewRef}
          searchProps={{
            switchList: [], //头部切换列表
            searchList,
            onSwitch,
            onReset,
            onSearch,
          }}
          actionList={actionList}
          tableProps={{
            columns: getTableColumn,
            dataSource: data?.rows, //mockData
            rowKey: 'id',
            loading: loading,
            pagination: pagination as any,
            onPageChange: onPageChange,
          }}
        />

        {/* 撤销弹窗 */}
        {invalidState?.isShow && (
          <RevokeModal
            resObj={invalidState?.resObj}
            revokeRequestUrl={'/assetInventoryDifference/revoke'}
            onClose={() => setInvalidState({})}
            reqBody={{
              id: invalidState?.resObj?.id,
              state: `${getTenantID()}${ILoadMapTypeAll?.ASSET_SUMMARY_STATUS}1000`,
            }}
            modalTip={
              <div style={{ color: '#000' }}>
                确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.inventoryTitle}</span>】的审核, 撤销后可重新提交！
              </div>
            }
            reloadRequest={reloadManage}
          />
        )}

        {/* 作废弹窗 */}
        {isShowCancelModal?.isShow && (
          <CancelModal
            checkRows={isShowCancelModal?.recordObj}
            cancelTypeDic={ILoadMapTypeAll.ASSET_CANCEL_STATUS}
            cancelFormTypeRequired={true}
            cancelFormReasonRequired={true}
            modalTitle={'作废申请'}
            cancelRequestUrl={'/assetInventoryDifference/cancel'}
            reloadManage={reloadManage}
            cancelRequestType="POST"
            cancelRequestBody={{ state: `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1004` }}
            onClose={() => {
              setIsShowCancelModal({
                isShow: false,
                signTitle: '',
              });
            }}
          />
        )}

        {/* 删除提示框 */}
        {openTipInfoModal?.showModal && (
          <TipsErrorModalNew
            // ref={tipErrorModalRef}
            modalLoading={deleteApplyManageLoading}
            onClose={tipOnClose}
            modalOnOK={() => {
              deleteApplyManageRun({
                id: openTipInfoModal.checkRowObj?.id,
                versionNum: openTipInfoModal.checkRowObj?.versionNum,
                state: `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1004`,
              });
            }}
            modalTip={'确认删除该申请，删除后不可恢复！'}
            tipTextColor="#000"
          />
        )}
      </div>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(AssetAcquisitionManageView);
